<template>
  <div v-if="!item.hidden">
    <!-- 情况一：只有一个可显示的子路由，并且父路由设置了alwaysShow，或者没有子路由 -->
    <template v-if="hasOneShowingChild(item.children, item) && (!onlyOneChild.children || onlyOneChild.noShowingChildren) && !item.meta?.alwaysShow">
      <el-menu-item :index="resolvePath(onlyOneChild.path)">
        <el-icon v-if="onlyOneChild.meta?.icon || item.meta?.icon"><component :is="onlyOneChild.meta?.icon || item.meta?.icon" /></el-icon>
        <template #title><span>{{ onlyOneChild.meta?.title }}</span></template>
      </el-menu-item>
    </template>

    <!-- 情况二：有多个子路由，渲染成子菜单 -->
    <el-sub-menu v-else ref="subMenu" :index="resolvePath(item.path)">
      <template #title>
        <el-icon v-if="item.meta && item.meta.icon"><component :is="item.meta.icon" /></el-icon>
        <span>{{ item.meta?.title }}</span>
      </template>
      <sidebar-item
          v-for="child in item.children"
          :key="child.path"
          :is-nest="true"
          :item="child"
          :base-path="resolvePath(item.path)"
      />
    </el-sub-menu>
  </div>
</template>

<script>
import path from 'path-browserify'

export default {
  name: 'SidebarItem',
  props: {
    item: { type: Object, required: true },
    isNest: { type: Boolean, default: false },
    basePath: { type: String, default: '' }
  },
  data() {
    return {
      onlyOneChild: null
    }
  },
  methods: {
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter(item => {
        if (item.hidden) return false
        else {
          this.onlyOneChild = item
          return true
        }
      })
      if (showingChildren.length === 1) return true
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }
      return false
    },
    resolvePath(routePath) {
      if (/^(https?|mailto|tel):/.test(routePath)) {
        return routePath
      }
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>
